@echo off
chcp 65001 >nul
setlocal enabledelayedexpansion

:: PPH系统服务启动脚本
:: 支持断电重启、崩溃重启、错误重启

echo ========================================
echo PPH Services Startup
echo ========================================
echo.

set "DEPLOY_DIR=%~dp0.."
set "CONFIG_DIR=%DEPLOY_DIR%\config"

echo [INFO] Starting PPH production services...
echo [INFO] Deploy directory: %DEPLOY_DIR%
echo.

:: 检查管理员权限
net session >nul 2>&1
if %errorlevel% neq 0 (
    echo [ERROR] Administrator privileges required
    echo Please run this script as Administrator
    pause
    exit /b 1
)

:: 检查Node.js版本（严格检查18.17.1）
echo [INFO] Checking Node.js version...
for /f "tokens=*" %%i in ('node --version') do set NODE_VERSION=%%i
echo Current Node.js version: %NODE_VERSION%

:: 检查是否为18.17.1
echo %NODE_VERSION% | findstr "v18\.17\.1" >nul 2>&1
if %errorlevel% neq 0 (
    echo [ERROR] Node.js 18.17.1 is required!
    echo Current version: %NODE_VERSION%
    echo.
    echo ❌ Forbidden versions: 22.x, 20.x, 19.x (will cause sqlite3 incompatibility)
    echo ✅ Required version: 18.17.1 (exact version)
    echo.

    :: 尝试使用nvm切换到18.17.1
    echo [INFO] Attempting to switch to Node.js 18.17.1...
    nvm use 18.17.1 >nul 2>&1
    if %errorlevel% neq 0 (
        echo [ERROR] Failed to switch to Node.js 18.17.1
        echo.
        echo Please install Node.js 18.17.1:
        echo   1. Download: https://nodejs.org/dist/v18.17.1/node-v18.17.1-x64.msi
        echo   2. Or use nvm: nvm install 18.17.1 && nvm use 18.17.1
        echo.
        echo After installation, restart this script.
        pause
        exit /b 1
    )

    :: 验证切换成功
    for /f "tokens=*" %%i in ('node --version') do set NEW_NODE_VERSION=%%i
    echo %NEW_NODE_VERSION% | findstr "v18\.17\.1" >nul 2>&1
    if %errorlevel% neq 0 (
        echo [ERROR] Version switch failed. Still using: %NEW_NODE_VERSION%
        echo Please restart command prompt and try again.
        pause
        exit /b 1
    )
    echo [OK] Successfully switched to Node.js 18.17.1
) else (
    echo [OK] Node.js 18.17.1 detected - correct version!
)

:: 检查PM2
pm2 --version >nul 2>&1
if %errorlevel% neq 0 (
    echo [ERROR] PM2 not found
    echo Please run install-dependencies.bat first
    pause
    exit /b 1
)

:: 进入部署目录
cd /d "%DEPLOY_DIR%"

:: 停止现有服务
echo [STEP 1] Stopping Existing Services
echo ========================================

echo [INFO] Stopping existing PM2 processes...
pm2 stop all >nul 2>&1
pm2 delete all >nul 2>&1
echo [OK] Existing services stopped
echo.

:: 清理端口冲突
echo [STEP 2] Cleaning Port Conflicts
echo ========================================

echo [INFO] Checking and cleaning port conflicts...

:: 检查并清理3010端口
for /f "tokens=5" %%a in ('netstat -ano ^| findstr :3010 ^| findstr LISTENING') do (
    echo [INFO] Killing process on port 3010: %%a
    taskkill /f /pid %%a >nul 2>&1
)

:: 检查并清理3011端口
for /f "tokens=5" %%a in ('netstat -ano ^| findstr :3011 ^| findstr LISTENING') do (
    echo [INFO] Killing process on port 3011: %%a
    taskkill /f /pid %%a >nul 2>&1
)

:: 检查并清理3012端口
for /f "tokens=5" %%a in ('netstat -ano ^| findstr :3012 ^| findstr LISTENING') do (
    echo [INFO] Killing process on port 3012: %%a
    taskkill /f /pid %%a >nul 2>&1
)

echo [OK] Port conflicts cleared
echo.

:: 创建必要目录
echo [STEP 3] Creating Required Directories
echo ========================================

if not exist "app\logs" mkdir "app\logs"
if not exist "D:\PPH-Backups" mkdir "D:\PPH-Backups"
echo [OK] Required directories created
echo.

:: 设置环境变量
echo [STEP 4] Setting Environment Variables
echo ========================================

set NODE_ENV=production
set NODE_PATH=%CD%\node_modules
set PATH=%NODE_PATH%\.bin;%PATH%

echo [OK] Environment variables set
echo.

:: 启动服务
echo [STEP 5] Starting Services with PM2
echo ========================================

echo [INFO] Starting services using ecosystem configuration...

:: 检查配置文件
if not exist "%CONFIG_DIR%\ecosystem.config.cjs" (
    echo [ERROR] PM2 configuration file not found
    echo Expected: %CONFIG_DIR%\ecosystem.config.cjs
    pause
    exit /b 1
)

:: 启动所有服务
pm2 start "%CONFIG_DIR%\ecosystem.config.cjs" --env production
if %errorlevel% neq 0 (
    echo [ERROR] Failed to start services
    echo Check configuration and try again
    pause
    exit /b 1
)

echo [OK] Services started successfully
echo.

:: 保存PM2配置
echo [STEP 6] Saving PM2 Configuration
echo ========================================

pm2 save
if %errorlevel% neq 0 (
    echo [WARNING] Failed to save PM2 configuration
) else (
    echo [OK] PM2 configuration saved
)
echo.

:: 配置自动启动
echo [STEP 7] Configuring Auto-startup
echo ========================================

echo [INFO] Configuring PM2 auto-startup...

:: 尝试配置Windows启动
pm2-windows-startup install >nul 2>&1
if %errorlevel% equ 0 (
    echo [OK] Windows auto-startup configured
) else (
    echo [INFO] Trying alternative startup method...
    pm2 startup windows >nul 2>&1
    if %errorlevel% equ 0 (
        echo [OK] Alternative auto-startup configured
    ) else (
        echo [WARNING] Auto-startup configuration failed
        echo Services will need to be started manually after reboot
    )
)
echo.

:: 等待服务启动
echo [STEP 8] Waiting for Services to Initialize
echo ========================================

echo [INFO] Waiting for services to start...
timeout /t 15 /nobreak >nul
echo [OK] Initialization wait completed
echo.

:: 验证服务状态
echo [STEP 9] Verifying Service Status
echo ========================================

echo [INFO] Checking PM2 process status...
pm2 list

echo.
echo [INFO] Checking port status...

:: 检查前端端口
netstat -an | findstr :3010 | findstr LISTENING >nul
if %errorlevel% equ 0 (
    echo [OK] Frontend service (port 3010) is running
) else (
    echo [WARNING] Frontend service (port 3010) not detected
)

:: 检查后端端口
netstat -an | findstr :3011 | findstr LISTENING >nul
if %errorlevel% equ 0 (
    echo [OK] Backend service (port 3011) is running
) else (
    echo [WARNING] Backend service (port 3011) not detected
)

:: 检查管理端口
netstat -an | findstr :3012 | findstr LISTENING >nul
if %errorlevel% equ 0 (
    echo [OK] Management service (port 3012) is running
) else (
    echo [WARNING] Management service (port 3012) not detected
)
echo.

:: 健康检查
echo [STEP 10] Health Check
echo ========================================

echo [INFO] Performing backend health check...
timeout /t 5 /nobreak >nul

curl -s http://localhost:3011/api/health >nul 2>&1
if %errorlevel% equ 0 (
    echo [OK] Backend health check passed
) else (
    echo [WARNING] Backend health check failed
    echo Service may still be starting up
)
echo.

:: 显示访问信息
echo ========================================
echo SERVICES STARTED SUCCESSFULLY!
echo ========================================
echo.
echo Access URLs:
echo - Frontend Application: http://localhost:3010
echo - Backend API: http://localhost:3011/api
echo - Management Interface: http://localhost:3012
echo.
echo Management Commands:
echo - Check status: pm2 list
echo - View logs: pm2 logs
echo - View specific log: pm2 logs [service-name]
echo - Restart all: pm2 restart all
echo - Restart specific: pm2 restart [service-name]
echo - Stop all: pm2 stop all
echo - Monitor: pm2 monit
echo.
echo Service Names:
echo - pph-backend
echo - pph-frontend  
echo - pph-management
echo.
echo Log Files:
echo - Backend: app\logs\pph-backend-*.log
echo - Frontend: app\logs\pph-frontend-*.log
echo - Management: app\logs\pph-management-*.log
echo.

pause
